package com.simple.relaxed.manager.impl;

import com.simple.relaxed.anno.Mark;
import com.simple.relaxed.anno.Slice;
import com.simple.relaxed.exception.AnnotationAbsenceException;
import com.simple.relaxed.manager.AbstractManager;
import lombok.Data;
import ohos.aafwk.ability.AbilitySlice;

import java.util.HashMap;
import java.util.Map;

/**
 * 此对象中管理着，PageAbility中可以使用的所有AbilitySlice对象
 */
@Mark(methodName = "getInstance")
public class SliceManager extends AbstractManager<String, Map<Class<? extends AbilitySlice>, SliceManager.Entry>> {

    @Data
    public static class Entry {

        /**
         * Slice得路由绑定值
         */
        private String route;

        /**
         * Slice对象
         */
        private AbilitySlice slice;
    }

    private static SliceManager sliceManager = new SliceManager();

    private SliceManager() {
        super();
    }

    public static SliceManager getInstance() {
        if (sliceManager == null) {
            sliceManager = new SliceManager();
        }
        return sliceManager;
    }

    public void register(String bindName, String route, AbilitySlice abilitySlice) {
        Map<Class<? extends AbilitySlice>, Entry> lookup = lookup(bindName);
        if (lookup == null) {
            lookup = new HashMap<>();
            register(bindName, lookup);
        }
        Entry entry = new Entry();
        entry.setRoute(route);
        entry.setSlice(abilitySlice);
        lookup.put(abilitySlice.getClass(), entry);
    }

    public void unregister(String bindName, Class<? extends AbilitySlice> clazz) {
        Map<Class<? extends AbilitySlice>, Entry> lookup = lookup(bindName);
        if (lookup == null) {
            return;
        }
        lookup.remove(clazz);
    }

    @Override
    public void unregister(String s) {
        Map<Class<? extends AbilitySlice>, Entry> lookup = lookup(s);
        if (lookup == null) {
            return;
        }
        if (!lookup.isEmpty()) {
            lookup.clear();
        }
        super.unregister(s);
    }

    public AbilitySlice lookup(Class<? extends AbilitySlice> clazz) {
        Slice slice = clazz.getDeclaredAnnotation(Slice.class);
        if (slice == null) {
            throw new AnnotationAbsenceException("找不到注解".concat(Slice.class.getName()));
        }
        Map<Class<? extends AbilitySlice>, Entry> abilitySliceMap = map.get(slice.bindName());
        Entry entry = abilitySliceMap.get(clazz);
        return entry == null ? null : entry.getSlice();
    }

    @Override
    public void clear() {
        if (map.isEmpty()) {
            return;
        }
        for (Map.Entry<String, Map<Class<? extends AbilitySlice>, Entry>> entry : map.entrySet()) {
            Map<Class<? extends AbilitySlice>, Entry> value = entry.getValue();
            if (value == null || value.isEmpty()) {
                continue;
            }
            value.clear();
        }
        super.clear();
    }
}
